<?php

require_once 'MPDOStorage.php';
require_once 'interface/IMDebug.php';
require_once 'PHPTAL/TranslationService.php';

/**
 *
 */
class MTranslator implements PHPTAL_TranslationService, debuggable
{

	private $_vars = array();
	public $_currentDomain = 1; //default "moreia" domain at sqlite main.sl database
	private $_encoding = 'UTF-8';
	private $_lg = 'en';
	private $debug = false;
	public $error = null;

	public function __construct()
	{
	}

	public function setEncoding($enc)
	{
		$this->_encoding = $enc;
	}

	public function setLanguage()
	{
		$arLangs = array("en" => array("en", "en_GB", "en_GB.utf8"),
 						 "pt" => array("pt", "pt_BR", "pt_PT", "pt_BR.utf8")
		);
		$langs = func_get_args();
		$found = false;
		foreach ($langs as $langCode){
			putenv("LANG=$langCode");
			putenv("LC_ALL=$langCode");
			putenv("LANGUAGE=$langCode");
			$found = setlocale(LC_ALL, $langCode);
			if ($found) {
				foreach ($arLangs as $klg => $vlg){
					if(in_array($found, $vlg))
					$this->_lg = $klg;
				}
				//echo "locale is [$found]<br>";
				//echo "lg is [$this->_lg]<br>";
				break;
			}
		}
		if (!$found){
			$err = 'Language(s) code(s) "%s" not supported by your system';
			$err = sprintf($err, join(',', $langs));
			throw new Exception($err);
		}
	}
	/**
	 * Method used to return the current iso language code
	 * @return string
	 */
	public function getLang(){
		return $this->_lg;
	}
	/**
	 *
	 */
	public function addDomain($domain, $forceRollBack=false)
	{
		if(!is_string($domain))throw new MException("Domain name must be a string!");


		if($dbResource !== null)
		$dbh = $dbResource;
		else
		$dbh = MPDOStorage::instance();

			
		try{
			//if($autocommit):
			$dbh->beginTransaction();
				
			$res = $dbh->exec("INSERT INTO i18n_domain (domain_name) VALUES ('$domain')");

			if(!$forceRollBack)
			$dbh->commit();
			else
			$dbh->rollBack();
				
			//return $res;
			return true;
			//else:
			//	$res = $dbh->exec("INSERT INTO i18n_domain (domain_name) VALUES ('$domain')");
			//endif;

		} catch (PDOException $pe){
			$dbh->rollBack();
			print $pe;
			return false;
		} catch (MException $e){
			$dbh->rollBack();
			print $e;
			return false;
		}
		/*bindtextdomain($domain, $path);
		 if ($this->_encoding){
		 bind_textdomain_codeset($domain, $this->_encoding);
		 }
		 $this->useDomain($domain);*/
		//throw new MException("Method addDomain is not implemented.");
	}

	public function useDomain($domain)
	{
		if(!is_string($domain)) $this->_currentDomain = 1;

		try{
			$dbh = MPDOStorage::instance();
			$res = $dbh->query("SELECT id FROM i18n_domain WHERE domain_name LIKE '$domain'");
			$row = $res->fetch();
			$this->_currentDomain = $row['id'];

		} catch (PDOException $pe){
			print $pe . ($this->debug ? $res->errorInfo() : '');
		} catch (MException $e){
			print $e;
		}

		/*$old = $this->_currentDomain;
		 $this->_currentDomain = $domain;
		 textdomain($domain);
		 return $old;*/
		//throw new MException("Method useDomain is not implemented.");
	}

	public function getDomains(){

		$sql = "SELECT id,domain_name FROM i18n_domain";
		$dbh = MPDOStorage::instance();
		//var_dump($dbh);
		//echo "<br>$sql<br>";
		$res = $dbh->query($sql);
		//var_dump($res);
		$row = $res->fetchAll();
		if ($row)
		return $row;
		else
		return null;
	}
	public function setVar($key, $value)
	{
		$this->_vars[$key] = $value;
	}

	public function translate($key, $htmlencode=true)
	{

		$sql = "SELECT msgstr FROM i18n_translation_".$this->_lg." WHERE msgid LIKE '$key' AND domain_fid = ".$this->_currentDomain;

		$dbh = MPDOStorage::instance();
		//var_dump($dbh);
		//echo "<br>$sql<br>";
		$res = $dbh->query($sql);
		//var_dump($res);
		$row = $res->fetch();
			
		if(!$row['msgstr'])
		$value = $key;
		else
		$value = $row['msgstr'];
		//$value = gettext($key);

		if ($htmlencode){
			$value = htmlspecialchars($value, ENT_QUOTES, $this->_encoding);
		}
		while (preg_match('/\${(.*?)\}/sm', $value, $m)){
			list($src,$var) = $m;
			if (!array_key_exists($var, $this->_vars)){
				$err = sprintf('Interpolation error, var "%s" not set', $var);
				throw new Exception($err);
			}
			$value = str_replace($src, $this->_vars[$var], $value);
		}
		return $value;
	}

	public function getList($domain_id = 1){

		$dbh = MPDOStorage::instance();
		$sql ="SELECT * FROM i18n_translation_".$this->_lg." WHERE domain_fid = $domain_id";
		//var_dump($dbh);
		//echo "<br>$sql<br>";
		$res = $dbh->query($sql);
		$list = '<dl>';
		$arList = array();
		//var_dump($dbh);
		while ($row = $res->fetch()) {
			//$list .= '<dt>' . $row['msgid'] . ' - ' . $row['msgstr'] . '<a href="&edit='.$row['msgid'].'" border="0"><img src="images/edit.gif" /></a><a href="&delete='.$row['msgid'].'" border="0"><img src="images/delete_icon.gif" /></a></dt>';
			$arList[] = array("id" => $row["id"], "msgid" => $row['msgid'], "msgstr" => $row['msgstr']);
		}
		//var_dump($arList);
		$list .= '</dl>';

		return $arList;
	}
	public function editListResult($id, $update = false){
		if(!$id) return null;

		$dbh = MPDOStorage::instance();
		if(!$update)
		$sql = "SELECT * FROM i18n_translation_".$this->_lg." WHERE id = $id";
		else
		$sql = "UPDATE i18n_translation_".$this->_lg." set msgstr = '$update' WHERE id = $id";
		//echo "[$sql]";
		$res = $dbh->query($sql);
		if(!is_bool($res)) $row = $res->fetch();

		if(!$update):
		return array("msgid" => $row['msgid'], "msgstr" => $row['msgstr']);
		else:
		//var_dump($row);
		//return $row;
		return $res;
		endif;


	}
	public function editTranslation($id, $newText){
		if(!$id) return null;

		$id = (int)$id;

		$dbh = MPDOStorage::instance();
		try{
			$sql = "UPDATE i18n_translation_".$this->_lg." SET msgstr = '$newText' WHERE id = $id";

			$res = $dbh->query($sql);
			if($this->debug):
			echo "$sql<br/>";
			echo "  ".var_dump($dbh->errorInfo());
			endif;
			return $res;
				
		}catch (PDOException $e){
			if($this->debug):
			echo "$sql<br/>";
			echo $e->getMessage();
			var_dump($dbh->errorInfo());
			endif;
			return false;
		}
			
	}

	public function hasTranslationID($msgid, $domain_id=null){
		$sql = "SELECT msgstr FROM i18n_translation_".$this->_lg." WHERE msgid LIKE '$msgid' AND domain_fid = ".(null===$domain_id ?$this->_currentDomain:$domain_id);
		$dbh = MPDOStorage::instance();
		$res = $dbh->query($sql);

		if ($res->fetch())
		return True;
		else
		return False;
	}

	public function addTranslation($msgid, $msgstr, $domain_id=null){
		if ($this->hasTranslationID($msgid, $domain_id)) return false;

		$domain_id = (null===$domain_id ?$this->_currentDomain:$domain_id);

		$dbh = MPDOStorage::instance();

		$sql = "SELECT max(id) as last_id FROM i18n_translation_".$this->_lg;
		$res = $dbh->query($sql);
		$nu = $res->fetch();
		$nu = (int)$nu['last_id'];
		$nextID = $nu+1;

		//$sql = "INSERT INTO i18n_translation_".$this->_lg." (id, domain_fid, msgid, msgstr) VALUES($nextID, $domain_id, '$msgid', '$msgstr')";
		$sql = "INSERT INTO i18n_translation_".$this->_lg." (id, domain_fid, msgid, msgstr) VALUES(:nextID, :domain_id, :msgid, :msgstr)";

		$stmt = $dbh->prepare($sql);
		$stmt->bindParam(':nextID', $nextID, PDO::PARAM_INT);
		$stmt->bindParam(':domain_id', $domain_id, PDO::PARAM_STR);
		$stmt->bindParam(':msgid', $dbh->quote($msgid), PDO::PARAM_STR);
		$stmt->bindParam(':msgstr', $dbh->quote($msgstr), PDO::PARAM_STR);
		$res = $stmt->execute();

		//$res = $dbh->query($sql);
		//$this->error = $dbh->errorInfo();
		$this->error = $stmt->errorInfo();
		if($this->debug):
		echo "$sql<br/>";
		//echo "  ".var_dump($dbh->errorInfo());
		echo "  ".var_dump($stmt->errorInfo());
		endif;
			
		return $res;
	}
	public function setDebug($bool){
		if(!is_bool($bool)) $this->debug = false;

		$this->debug = $bool;
	}
}
?>